package common

import io.netty.channel.Channel
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.experimental.CoroutineContext

/**
 * channel管理类
 * @author King
 */
class ChannelManager {
    /**channel */
    var channelMap: MutableMap<Long, NetChannel> = ConcurrentHashMap()


    /**
     * 添加一个连接
     * @param channel
     */
    fun addChannel(channel: Channel) {
        val netChannel = NetChannel(channel)
        this.channelMap.put(netChannel.channelId, netChannel)
    }


    /**
     * 添加一个连接
     * @param channel
     */
    fun addCoroutineChannel(context: CoroutineContext,channel: Channel) {
        val netChannel = NetChannel(context,channel)
        this.channelMap.put(netChannel.channelId, netChannel)
    }


    /**
     * 删除一个连接
     * @param channel
     */
    fun delChannel(channel: Channel) {
        val attribute = channel.attr(ServerAttributeKey.channel_Id)
        if (attribute == null) {
            log.error("delete a channel without id")
            return
        }
        var netChannel = this.channelMap.remove(attribute.get())
        netChannel?.let { it.destory() }
        println("delete a channel")
    }

    companion object {
        private val log = LoggerFactory.getLogger(ChannelManager::class.java)
    }
}
